//
//  SetSystemInfomationViewController.m
//  PYWGetColor
//
//  Created by 杜文杰 on 2018/6/17.
//  Copyright © 2018年 dwj. All rights reserved.
//

#import "SetSystemInfomationViewController.h"
#import "SetSysInfoTableViewCell.h"
#import "SetSysExitLoginTableViewCell.h"
#import "UserModel.h"
#import "HomePageViewController.h"
#import "GetMessagesTableViewCell.h"
#import "AboutUsViewController.h"
#import "JPUSHService.h"

@interface SetSystemInfomationViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *mainTableView; // 主框架
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *footerView;

@property (nonatomic, strong) UIButton *makesureBtn;
@property (nonatomic, strong) NSMutableArray *muDataArray;
@property (nonatomic, assign) BOOL isOn;
@end

@implementation SetSystemInfomationViewController
- (void)switchMessage {
    [[AFAppDotNetAPIClient sharedClient] POST:@"interface.php?m=switchmessage" parameters:@{@"uid":[UserModel sharedInstanced].userId,@"token":[UserModel sharedInstanced].token,@"status":self.isOn?@"1":@"2"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"error_code"]];
        if ([str isEqualToString:@"0"]) {
            ShowMessage(@"操作成功");
        }else{
            ShowMessage(@"操作失败");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.title = @"设置";
    [self.view addSubview:self.mainTableView];
    
}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.muDataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *dataArray = self.muDataArray[section];
    return dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        GetMessagesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([GetMessagesTableViewCell class])];
        cell.switchBtnBlock = ^(BOOL isOn) {
            if (isOn) {
                NSLog(@"开关是开的");
            }else{
                NSLog(@"开关是关的");
            }
            self.isOn = isOn;
            [self switchMessage];
        };
        return cell;
    }
    if (indexPath.section == 3) { // 退出登录
        SetSysExitLoginTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SetSysExitLoginTableViewCell class])];
        cell.exitBtnBlock = ^{
            [UserModel sharedInstanced].userId = @"";
            [UserModel sharedInstanced].headImg = @"";
            [UserModel sharedInstanced].nameNick = @"";
            EMError *error = [[EMClient sharedClient] logout:YES]; //环信退出登录
            if (!error) {
                NSLog(@"退出成功");
            }
            
            HomePageViewController *VC = [[HomePageViewController alloc]init];
            [self.navigationController pushViewController:VC animated:YES];
            
            //退出的时候删除别名
            [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                if (iResCode == 0) {
                    NSLog(@"删除别名成功");
                }
            } seq:1];
        };
        return cell;
    }
    SetSysInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SetSysInfoTableViewCell class])];
    cell.dataDic = self.muDataArray[indexPath.section][indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50 / HEIGHT_6S_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16 / HEIGHT_6S_SCALE;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = getColor(dividerColor);
    
    return bgView;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = getColor(bgColor);
    return bgView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1 ) {
        if (indexPath.row == 0) {
            AboutUsViewController *VC = [[AboutUsViewController alloc]init];
            VC.typeStr = @"1";
            [self.navigationController pushViewController:VC animated:NO];
        }
        if (indexPath.row == 1) {
            AboutUsViewController *VC = [[AboutUsViewController alloc]init];
            VC.typeStr = @"2";
            [self.navigationController pushViewController:VC animated:NO];
        }
    }
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            [self clearBufferBtnClicked];
        }
    }
}
#pragma mark - init
- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - SafeAreaBottomHeight - SafeAreaTopHeight) style:UITableViewStyleGrouped];
        _mainTableView.backgroundColor = getColor(bgColor);
        _mainTableView.tableHeaderView = self.headerView;
        _mainTableView.tableFooterView = self.footerView;
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        // 动态行高
        _mainTableView.rowHeight = UITableViewAutomaticDimension;
        // 预估行高
        _mainTableView.estimatedRowHeight = 80;
        [_mainTableView registerClass:[SetSysInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SetSysInfoTableViewCell class])];
        [_mainTableView registerClass:[SetSysExitLoginTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SetSysExitLoginTableViewCell class])];
        [_mainTableView registerClass:[GetMessagesTableViewCell class] forCellReuseIdentifier:NSStringFromClass([GetMessagesTableViewCell class])];
        
    }
    return _mainTableView;
}
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
        _headerView.backgroundColor = [UIColor grayColor];
    }
    return _headerView;
}
- (UIView *)footerView
{
    if (!_footerView) {
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.01)];
    }
    return _footerView;
}
- (NSMutableArray *)muDataArray
{
    if (!_muDataArray) {
//        _muDataArray = @[@[@{@"titleName":@"关于帮你",@"inputValue":@""}.mutableCopy,
//                           @{@"titleName":@"用户指南",@"inputValue":@""}.mutableCopy
//                           ].mutableCopy,
//                         @[@{@"titleName":@"接收消息",@"inputValue":@""}.mutableCopy].mutableCopy,
//                         @[@{@"titleName":@"版本更新",@"inputValue":@""}.mutableCopy,
//                           @{@"titleName":@"清楚缓存",@"inputValue":@""}.mutableCopy].mutableCopy,
//                         @[@{@"titleName":@"退出登录",@"inputValue":@""}.mutableCopy].mutableCopy,
//                         ].mutableCopy;
        _muDataArray = @[@[@{@"titleName":@"关于帮你",@"inputValue":@""}.mutableCopy,
                           @{@"titleName":@"用户指南",@"inputValue":@""}.mutableCopy
                           ].mutableCopy,
                         @[@{@"titleName":@"接收消息",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"清除缓存",@"inputValue":@""}.mutableCopy].mutableCopy,
                         @[@{@"titleName":@"退出登录",@"inputValue":@""}.mutableCopy].mutableCopy,
                         ].mutableCopy;
    }
    return _muDataArray;
}
- (void)clearBufferBtnClicked{
    CGFloat size = [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSTemporaryDirectory()];
    
    NSString *message = size > 1 ? [NSString stringWithFormat:@"缓存%.0fM, 删除缓存", size] : [NSString stringWithFormat:@"缓存%.0fK, 删除缓存", size * 1024.0];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) {
        [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject];
        [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject];
        [self cleanCaches:NSTemporaryDirectory()];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:action];
    [alert addAction:cancel];
    [self showDetailViewController:alert sender:nil];
}
// 计算目录大小
- (CGFloat)folderSizeAtPath:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *manager = [NSFileManager defaultManager];
    CGFloat size = 0;
    if ([manager fileExistsAtPath:path]) {
        // 获取该目录下的文件，计算其大小
        NSArray *childrenFile = [manager subpathsAtPath:path];
        for (NSString *fileName in childrenFile) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
        }
        // 将大小转化为M
        return size / 1024.0 / 1024.0;
    }
    return 0;
}

// 根据路径删除文件
- (void)cleanCaches:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        // 获取该路径下面的文件名
        NSArray *childrenFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childrenFiles) {
            // 拼接路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            // 将文件删除
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}
@end

